; This file is the part of the Textator project
; Last changed: $Id: tkn_getchar.asm 82 2009-12-08 20:53:44Z vitamin.caig $
; (C) Vitamin/CAIG/2001

; Specifies function, which can be used to processing tokenized text,
; retrieving symbols one-by-one

; tiny text model (up to 3840 bytes of local texts)
; 2 bytes per token
; Label LocalBase should point to local text start

; SjASM format used

        macro DEFTOKEN id
id      equ $
        endm

        ifdef TINYTEXT
TKNBASE equ 14
TKNEND  equ 31

; Test for token
; return if ordinal text
; de - token text, hl - continue if token
        macro TESTTOKEN
        cp TKNBASE
        ret c
        cp TKNEND+1
        ret nc
        add a,(high LocalBase)-TKNBASE
        ld d,a
        ld e,(hl)
        inc hl
        endm

        macro TOKEN id
        db TKNBASE+(high id)-(high LocalBase),low id
        endm

        else
; Huge text model
TKNCODE equ 16

        macro TESTTOKEN
        cp TKNCODE
        ret nz
        ld d,(hl)
        inc hl
        ld e,(hl)
        inc hl
        endm

; BigEndian for compatibility with other source
        macro TOKEN id
        db TKNCODE,high id,low id
        endm
        endif

;In: HL- initial text
;Out: A- char. 0 if end
;HL is updated, should be keeped for next iteration until end
StrGetChar
        ld a,(hl)
        inc hl
        and a
        jr z,PopCtx
        TESTTOKEN
        push de
        ex de,hl
StrSP   equ $+1
        ld a,0
        inc a
        ld (StrSP+1),a
        dec a
        add a,a
        add a,low StrStack
        ld l,a
        ld h,high StrStack
        ld (hl),e
        inc l
        ld (hl),d
        pop hl
        jr StrGetChar
PopCtx  ld a,(StrSP)
        and a
        ret z   ;real end
        dec a
        ld (StrSP),a
        add a,a
        add a,low StrStack
        ld l,a
        ld h,high StrStack
        ld a,(hl)
        inc l
        ld h,(hl)
        ld l,a
        jr StrGetChar

        org (($-1)/256+1)*256
StrStack
        ds 16           ;assume that 8-level-deep is enough
